import argparse
import json
import os
from executor.dsl_executor import DSLExecutor


def main() -> None:
    parser = argparse.ArgumentParser(description="Run a demo DSL flow against logs and generate config")
    parser.add_argument("--flow", required=True, help="Path to DSL YAML flow file")
    parser.add_argument("--log", default="sample_logs/LogDump/app.log", help="Path to the app.log file")
    parser.add_argument("--auto-approve", action="store_true", default=True, help="Auto approve human-in-loop step")
    args = parser.parse_args()

    workspace_root = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
    templates_dir = os.path.join(workspace_root, "DSL", "templates")
    validators_dir = os.path.join(workspace_root, "DSL", "validators")
    out_dir = os.path.join(workspace_root, "DSL", "out")

    executor = DSLExecutor(
        workspace_root=workspace_root,
        templates_dir=templates_dir,
        validators_dir=validators_dir,
        out_dir=out_dir,
    )
    result = executor.run(flow_yaml_path=args.flow, log_path=args.log, auto_approve=args.auto_approve)
    print("Flow:", result["flow_id"]) 
    if "final_state" in result:
        print("Final State:", result["final_state"]) 
        if result.get("final_state_message"):
            print("Final Message:", result["final_state_message"]) 
    if "evidence_count" in result:
        print("Evidence Count:", result["evidence_count"]) 
    print("Artifacts:")
    for p in result["artifacts"]:
        print(" -", p)
    print("Report:", result["report"]) 
    # 打印简要轨迹
    try:
        with open(result["report"], "r", encoding="utf-8") as rf:
            report = json.load(rf)
        trace = report.get("trace", [])
        if trace:
            print("Trace:")
            for step in trace:
                name = step.get("name")
                action = step.get("action")
                ok = step.get("approved", step.get("ok"))
                msg = step.get("message")
                suffix = f" (ok={ok})" if ok is not None else ""
                if msg:
                    print(f" - {action} -> {name}{suffix} | {msg}")
                else:
                    print(f" - {action} -> {name}{suffix}")
        # 若 note.json 存在，读取其中的 message 并打印
        out_dir = os.path.join(os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)), "DSL", "out")
        note_path = os.path.join(out_dir, "note.json")
        if os.path.exists(note_path):
            with open(note_path, "r", encoding="utf-8") as nf:
                note = json.load(nf)
            msg = note.get("message")
            if msg:
                print("Message:", msg)
    except Exception:
        pass


if __name__ == "__main__":
    main()

